from flask import Flask
from .models import local_settings
from .models.models import Dbconn
from flask_login import LoginManager, UserMixin, current_user


class LoginUser(UserMixin):
    def __init__(self, luser):
        self.id = luser.get('id')
        self.name = luser.get('name')
        self.role = luser.get('role')

    def get_name(self):
        return self.name

    def get_id(self):
        return self.id

    @staticmethod
    def get_user(uid):
        db = Dbconn()
        luser = db.get_user(uid)
        if luser:
            return LoginUser({'id': uid, 'name': luser.name, 'role': luser.role})


def create_app():
    app = Flask(__name__)
    app.config.from_pyfile('config.cfg')
    login = LoginManager(app)
    login.login_view = 'main.login'

    @login.user_loader
    def load_user(uid):
        return LoginUser.get_user(uid)

    from .routes import main, purchase
    app.register_blueprint(main.bp)
    app.register_blueprint(purchase.pbp)
    return app
